package kordegi.forumsystem.controller;

import io.jsonwebtoken.lang.Assert;
import kordegi.forumsystem.common.dto.LoginDto;
import kordegi.forumsystem.common.lang.Result;
import kordegi.forumsystem.entity.User;
import kordegi.forumsystem.service.Impl.UserServiceImpl;
import kordegi.forumsystem.util.JwtUtils;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author kordegi
 * @date 2022.05.01 20:41
 * @Description
 */

@RestController
public class LogController {
    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserServiceImpl userService;

    @CrossOrigin
    @PostMapping("/user/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {

        User userMap = userService.login(loginDto.getUsername());
        Assert.notNull(userMap, "用户不存在");

        if(!userMap.getPassword().equals(loginDto.getPassword())) {
            return Result.fail("密码错误");
        }

        String jwt = jwtUtils.createToken(userMap.getId());

        response.setHeader("Authorization", jwt);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");

        Map<String, Object> map = new HashMap<>();
        map.put("id", userMap.getId());
        map.put("username", userMap.getUsername());
        map.put("password", userMap.getPassword());
        map.put("phonenumber", userMap.getPhonenumber());
        map.put("email", userMap.getEmail());
        return Result.succ("登陆成功",map);
    }

    @RequestMapping("/logout")
    @RequiresAuthentication
    public Result logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SecurityUtils.getSubject().logout();
        request.getSession().setAttribute("user",null);
        response.sendRedirect("/home");

        return Result.succ(null);
    }

    @RequestMapping("/home")
    public Result home(){
        return Result.succ(null);
    }
}
